﻿using ERPSystem.Common.Domains.UserCommon;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;

namespace RBACWrite.API.Command.Roless
{
    public class PermissionRolesCreateHandler : IRequestHandler<PermissionRolesCreateCommon, Result>
    {
        private readonly IBaseRepository<RolesPermissions> rolesPermissionsRep;
        /// <summary>
        /// 添加权限角色
        /// </summary>
        /// <param name="rolesPermissionsRep"></param>
        public PermissionRolesCreateHandler(IBaseRepository<RolesPermissions> rolesPermissionsRep)
        {
            this.rolesPermissionsRep = rolesPermissionsRep;
        }
        /// <summary>
        /// 添加权限角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(PermissionRolesCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var n = new List<RolesPermissions>();
                foreach (var item in request.rolesIds)
                {
                    var rolePermission = new RolesPermissions()
                    {
                        PermissionsId = request.permissionsId,
                        RolesId = item
                    };
                    n.Add(rolePermission);
                }
                if (n == null)
                {
                    result.Msg = "添加失败";
                    return result;
                }
                await rolesPermissionsRep.AddRange(n);
                result.Code = (int)CommonErrorCode.Success;
                result.Msg = "添加成功";
            }
            catch (Exception)
            {
                result.Msg = "添加异常";
                throw;
            }
            return result;
        }
    }
}
